package kr.co.bettersoft.usedmarketandroid.common;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketChat;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketChatMessage;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketChatRecognition;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketChatUser;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketMember;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketSMS;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
/**
 * 채팅 관련 서버 메소드를 호출하는 rest 클래스이다.
 * @author blue
 *
 */
public class UsedMarketChatRest {
	String TAG = "UsedMarketChatRest";


	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 서버 통신

	/**
	 * RestRegisterChatAndRegisterUser	RegisterChatAndRegisterUser		registerChatAndRegisterUser
	 *  1. 채팅방을 생성한다.
	 *  2. 생성자를 사용자로 등록 한다.
	 * @return  String
	 */
	public UsedMarketChat RestRegisterChatAndRegisterUser(UsedMarketChat usedMarketChat){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_CONTROLLER+"/"+CommonConstant.REGISTER_CHAT_AND_REGISTER_USER;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("idUsedMarketProduct", usedMarketChat.getIdUsedMarketProduct());			// 물품 테이블 아이디.
			obj.put("owner", usedMarketChat.getOwner());										// 생성자 휴대전화번호.
			obj.put("activateYn", "Y");															// 활성화 여부. 기본값은 Y
			obj.put("modifyDate", nowDate);														// 수정 일자.
			obj.put("registerDate", nowDate);													// 등록 일자.
			obj.put("phoneNumber", usedMarketChat.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			
			Log.d(TAG,"getIdUsedMarketProduct():"+usedMarketChat.getIdUsedMarketProduct());
			Log.d(TAG,"getOwner():"+usedMarketChat.getOwner());
			Log.d(TAG,"getPhoneNumber():"+usedMarketChat.getPhoneNumber());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		Log.d(TAG,"callResult::"+callResult);
		
		UsedMarketChat resultUsedMarketChat = new UsedMarketChat();
		/*
		 * "idUsedMarketChat":null,
		 * "idUsedMarketProduct":null,
		 * "owner":null,
		 * "activateYn":null,
		 * "modifyDate":null,
		 * "registerDate":null,
		 * "totalCount":null,
		 * "result":"FAIL",
		 * "phoneNumber":null,
		 * "idUsedMarketChatUser":null,
		 * "usedMarketChatIdUsedMarketChat":null,
		 * "usedMarketChatIdUsedMarketProduct":null,
		 * "recognitionCount":null,
		 * "readYn":null,
		 * "otherUserNickName":null,
		 * "otherUserPhoneNumber":null,
		 * "thumbnailSmall":null}
		 */
		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);
				
				resultUsedMarketChat.setIdUsedMarketChat(checkNull(jsonObject.getString("result")));
				resultUsedMarketChat.setIdUsedMarketProduct(checkNull(jsonObject.getString("idUsedMarketProduct")));
				resultUsedMarketChat.setOwner(checkNull(jsonObject.getString("owner")));
				resultUsedMarketChat.setActivateYn(checkNull(jsonObject.getString("activateYn")));
				resultUsedMarketChat.setModifyDate(checkNull(jsonObject.getString("modifyDate")));
				resultUsedMarketChat.setRegisterDate(checkNull(jsonObject.getString("registerDate")));
				resultUsedMarketChat.setTotalCount(checkNull(jsonObject.getString("totalCount")));
				resultUsedMarketChat.setResult(checkNull(jsonObject.getString("result")));
				resultUsedMarketChat.setPhoneNumber(checkNull(jsonObject.getString("phoneNumber")));
				resultUsedMarketChat.setIdUsedMarketChatUser(checkNull(jsonObject.getString("idUsedMarketChatUser")));
				resultUsedMarketChat.setUsedMarketChatIdUsedMarketChat(checkNull(jsonObject.getString("usedMarketChatIdUsedMarketChat")));
				resultUsedMarketChat.setUsedMarketChatIdUsedMarketProduct(checkNull(jsonObject.getString("usedMarketChatIdUsedMarketProduct")));
				resultUsedMarketChat.setRecognitionCount(checkNull(jsonObject.getString("recognitionCount")));
				resultUsedMarketChat.setReadYn(checkNull(jsonObject.getString("readYn")));
				resultUsedMarketChat.setOtherUserNickName(checkNull(jsonObject.getString("otherUserNickName")));
				resultUsedMarketChat.setOtherUserPhoneNumber(checkNull(jsonObject.getString("otherUserPhoneNumber")));
				resultUsedMarketChat.setThumbnailSmall(checkNull(jsonObject.getString("thumbnailSmall")));
				
//				callResult = jsonObject.getString("result").toString(); 
			} catch (JSONException e) {
				resultUsedMarketChat.setResult("FAIL");
				e.printStackTrace();
			} 
		}else{
			resultUsedMarketChat.setResult("FAIL");
		}
		return resultUsedMarketChat;
	}

	/**
	 * RestSelectChat			selectChat
	 *  채팅방 정보를 가져 온다.
	 * @return  String
	 */
	public UsedMarketChat RestSelectChat(UsedMarketChat usedMarketChat){
		
		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();
		
		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_CONTROLLER+"/"+CommonConstant.SELECT_CHAT;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("activateYn", "Y");															// 활성화 여부. 기본값은 Y
			obj.put("owner", usedMarketChat.getOwner());							// 사용자(생성자) 휴대전화번호.
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();
		
		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);
		
		Log.d(TAG,"RestSelectChat callResult::"+callResult);
		
		/*
		 * 04-15 15:55:10.233: D/UsedMarketChatRest(1546): callResult::{
		 * "idUsedMarketChat":"15",
		 * "idUsedMarketProduct":"24",
		 * "owner":"01022173645",
		 * "activateYn":"Y",
		 * "modifyDate":"2014-04-15 15:55:10",
		 * "registerDate":"2014-04-15 15:55:10",
		 * 
		 * "totalCount":null,"result":null,"phoneNumber":null,
		 * "idUsedMarketChatUser":null,"usedMarketChatIdUsedMarketChat":null,
		 * "usedMarketChatIdUsedMarketProduct":null,"recognitionCount":null,
		 * "readYn":null,"otherUserNickName":null,"otherUserPhoneNumber":null,
		 * "thumbnailSmall":null,"content":null,"subject":null,"messageCount":null}
		 */
		UsedMarketChat resultUsedMarketChat = new UsedMarketChat();
//		 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);
				resultUsedMarketChat.setIdUsedMarketChat(checkNull(jsonObject.getString("idUsedMarketChat")));
				resultUsedMarketChat.setIdUsedMarketProduct(checkNull(jsonObject.getString("idUsedMarketProduct")));
				resultUsedMarketChat.setOwner(checkNull(jsonObject.getString("owner")));
				resultUsedMarketChat.setSubject(checkNull(jsonObject.getString("subject")));
				resultUsedMarketChat.setResult("SUCCESS");
			} catch (JSONException e) {
				resultUsedMarketChat.setResult("FAIL");
				e.printStackTrace();
			} 
		}else{
			resultUsedMarketChat.setResult("FAIL");
		}
		return resultUsedMarketChat;
	}
	
	/**
	 * RestSelectChatList			selectChatList	
	 *  채팅방 목록을 가져 온다.
	 * @return  String
	 */
	public String RestSelectChatList(UsedMarketChat usedMarketChat){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_CONTROLLER+"/"+CommonConstant.SELECT_CHAT_LIST;
		JSONObject obj = new JSONObject();
		try{		 
			Log.d(TAG,"phoneNumber:"+usedMarketChat.getPhoneNumber());
			obj.put("activateYn", "Y");															// 활성화 여부. 기본값은 Y
			obj.put("phoneNumber", usedMarketChat.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

//		Log.d(TAG,"callResult::"+callResult);
		/*
		 * {"idUsedMarketChat":"11",
		 * "idUsedMarketProduct":"40",
		 * "owner":"01022173645",
		 * 
		 * "activateYn":"Y",
		 * "modifyDate":"2014-04-11 15:25:52",
		 * "registerDate":"2014-04-11 15:25:52",
		 * 
		 * "totalCount":null,"result":null,"phoneNumber":null,"idUsedMarketChatUser":null,
		 * "usedMarketChatIdUsedMarketChat":null,"usedMarketChatIdUsedMarketProduct":null,
		 * 
		 * "recognitionCount":"0",
		 * "readYn":null,
		 * 
		 * "otherUserNickName":"하이",
		 * 
		 * "otherUserPhoneNumber":null,"thumbnailSmall":"",
		 * 
		 * "content":null,
		 * "subject":null,
		 * "messageCount":"0"},
		 * 
		 * 
		 * {"idUsedMarketChat":"10","idUsedMarketProduct":"40","owner":"01022173645","activateYn":"Y","modifyDate":"2014-04-10 17:45:16","registerDate":"2014-04-10 17:45:16","totalCount":null,"result":null,"phoneNumber":null,"idUsedMarketChatUser":null,"usedMarketChatIdUsedMarketChat":null,"usedMarketChatIdUsedMarketProduct":null,"recognitionCount":"1","readYn":"Y","otherUserNickName":"하이","otherUserPhoneNumber":null,"thumbnailSmall":"","content":"네네","subject":null,"messageCount":"1"},{"idUsedMarketChat":"8","idUsedMarketProduct":"40","owner":"01022173645","activateYn":"Y","modifyDate":"2014-04-10 17:43:25","registerDate":"2014-04-10 17:43:25","totalCount":null,"result":null,"phoneNumber":null,"idUsedMarketChatUser":null,"usedMarketChatIdUsedMarketChat":null,"usedMarketChatIdUsedMarketProduct":null,"recognitionCount":"1","readYn":"Y","otherUserNickName":"하이","otherUserPhoneNumber":null,"thumbnailSmall":"","content":null,"subject":null,"messageCount":"0"},{"idUsedMarketChat":"6","idUsedMarketProduct":"40","owner":"01022173645","activateYn":"Y","modifyDate":"2014-04-10 17:41:32","registerDate":"2014-04-10 17:41:32","totalCount":null,"result":null,"phoneNumber":null,"idUsedMarketChatUser":null,"usedMarketChatIdUsedMarketChat":null,"usedMarketChatIdUsedMarketProduct":null,"recognitionCount":"0","readYn":null,"otherUserNickName":"하이","otherUserPhoneNumber":null,"thumbnailSmall":"","content":null,"subject":null,"messageCount":"0"},{"idUsedMarketChat":"4","idUsedMarketProduct":"40","owner":"01022173645","activateYn":"Y","modifyDate":"2014-04-10 17:38:00","registerDate":"2014-04-10 17:38:00","totalCount":null,"result":null,"phoneNumber":null,"idUsedMarketChatUser":null,"usedMarketChatIdUsedMarketChat":null,"usedMarketChatIdUsedMarketProduct":null,"recognitionCount":"0","readYn":null,"otherUserNickName":"하이","otherUserPhoneNumber":null,"thumbnailSmall":"","content":null,"subject":null,"messageCount":"0"},{"idUsedMarketChat":"1","idUsedMarketProduct":"40","owner":"01022173645","activateYn":"Y","modifyDate":"2014-04-10 11:53:04","registerDate":"2014-04-10 11:53:04","totalCount":null,"result":null,"phoneNumber":null,"idUsedMarketChatUser":null,"usedMarketChatIdUsedMarketChat":null,"usedMarketChatIdUsedMarketProduct":null,"recognitionCount":"0","readYn":null,"otherUserNickName":"하이","otherUserPhoneNumber":null,"thumbnailSmall":"","content":null,"subject":null,"messageCount":"0"}]
		 * 
		 * 
		 * {"idUsedMarketChat":"1",
		 * "idUsedMarketProduct":"40",
		 * "owner":"01022173645",
		 * 
		 * "activateYn":"Y",
		 * 
		 * "modifyDate":"2014-04-10 11:53:04",
		 * "registerDate":"2014-04-10 11:53:04",
		 * 
		 * "totalCount":null,"result":null,"phoneNumber":null,
		 * "idUsedMarketChatUser":null,"usedMarketChatIdUsedMarketChat":null,"usedMarketChatIdUsedMarketProduct":null,
		 * 
		 * "recognitionCount":"0",
		 * "readYn":null,
		 * "otherUserNickName":"하이",
		 * 
		 * "otherUserPhoneNumber":null,
		 * 
		 * "thumbnailSmall":""},
		 * messageCount	등록된 메시지 갯수.
			content	마지막 대화 내용.
			subject	물품 등록 제목.
		 * 
		 */
		
		
		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}

	/**
	 * RestUpdateDeactivateChat			updateDeactivateChat	
	 *  채팅방을 비활성화 한다.
	 * @return  String
	 */
	public String RestUpdateDeactivateChat(UsedMarketChat usedMarketChat){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_CONTROLLER+"/"+CommonConstant.UPDATE_DEACTIVATE_CHAT;
		JSONObject obj = new JSONObject();
		try{
			obj.put("idUsedMarketChat", usedMarketChat.getIdUsedMarketChat());					// 채팅방 테이블 아이디.
			obj.put("idUsedMarketProduct", usedMarketChat.getIdUsedMarketProduct());			// 물품 테이블 아이디.
			obj.put("owner", usedMarketChat.getOwner());										// 생성자 휴대전화번호.
			obj.put("activateYn", "N");															// 활성화 여부. 기본값은 Y
			obj.put("modifyDate", nowDate);														// 수정 일자.
			obj.put("phoneNumber", usedMarketChat.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			
			Log.d(TAG,"idUsedMarketChat:"+usedMarketChat.getIdUsedMarketChat());
			Log.d(TAG,"idUsedMarketProduct:"+usedMarketChat.getIdUsedMarketProduct());
			Log.d(TAG,"owner:"+usedMarketChat.getOwner());
			Log.d(TAG,"phoneNumber:"+usedMarketChat.getPhoneNumber());
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

//		Log.d(TAG,"callResult::"+callResult);

		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);
				callResult = jsonObject.getString("result").toString(); 
			} catch (JSONException e) {
				callResult = "F";
				e.printStackTrace();
			} 
		}
		return callResult;
	}	

	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * RestRegisterRecognition			registerRecognition	 	
	 *  채팅방 인지 테이블에 등록 한다.
	 * @return  String
	 */
	public String RestRegisterRecognition(UsedMarketChatRecognition usedMarketChatRecognition){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_RECOGNITION_CONTROLLER+"/"+CommonConstant.REGISTER_RECOGNITION;
		JSONObject obj = new JSONObject();
		try{
			obj.put("phoneNumber", usedMarketChatRecognition.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			obj.put("readYn", "N");		
			obj.put("activateYn", "Y");		
			obj.put("modifyDate", nowDate);			
			obj.put("registerDate", nowDate);	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatRecognition.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		Log.d(TAG,"callResult::"+callResult);

		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}	

	/**
	 * RestSelectDuplicationRecognition			selectDuplicationRecognition	 	
	 *  인지 테이블에 등록되어 있는지 중복 확인한다.
	 * @return  String
	 */
	public String RestSelectDuplicationRecognition(UsedMarketChatRecognition usedMarketChatRecognition){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_RECOGNITION_CONTROLLER+"/"+CommonConstant.SELECT_DUPLICATION_RECOGNITION;
		JSONObject obj = new JSONObject();
		try{
			obj.put("phoneNumber", usedMarketChatRecognition.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			obj.put("activateYn", "Y");	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatRecognition.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

//		Log.d(TAG,"callResult::"+callResult);
		
		/*
		 * 04-11 17:22:17.902: D/UsedMarketChatRest(1905): callResult::{"idUsedMarketChatUser":"17","phoneNumber":"01022173645","activateYn":"Y","modifyDate":"2014-04-10 17:45:16","registerDate":"2014-04-10 17:45:16","usedMarketChatIdUsedMarketChat":"10","usedMarketChatIdUsedMarketProduct":"40","usedMarketChatOwner":"01022173645","totalCount":null,"result":null,"deviceType":"AS","pushId":"APA91bHDQMeiEetwQ5mwIGx_d0WRGoXXm8huRvHjFDjlznGPAcNMy3uf226v7h1L1biwEOKqw0vOc5dUDDmGIjB5vtanNACSuNgMqcj9KWS-6Dlsn5-bzKHbuji6Bhjk_nKs9bE5iat4nEIfydhInlNwQqvzorli8LPoNyn3CrEglE1zGXetWUA"}
		 * 04-11 17:22:17.952: D/UsedMarketChatRest(1905): callResult::{
		 * "idUsedMarketChatRecognition":null,
		 * "phoneNumber":null,"readYn":null,
		 * "activateYn":null,"modifyDate":null,
		 * "registerDate":null,"usedMarketChatIdUsedMarketChat":null,
		 * "usedMarketChatIdUsedMarketProduct":null,
		 * "usedMarketChatOwner":null,
		 * 
		 * "totalCount":"0",
		 * "result":null}
		 */

		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}	

	/**
	 * RestUpdateReadYn			updateReadYn	 	
	 *  인지 테이블의 메시지 읽음 여부를 업데이트 한다.
	 * @return  String
	 */
	public String RestUpdateReadYn(UsedMarketChatRecognition usedMarketChatRecognition){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_RECOGNITION_CONTROLLER+"/"+CommonConstant.UPDATE_READ_YN;
		JSONObject obj = new JSONObject();
		try{
			obj.put("phoneNumber", usedMarketChatRecognition.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			obj.put("readYn", "Y");		
			obj.put("activateYn", "Y");		
			obj.put("modifyDate", nowDate);			
			//			obj.put("registerDate", nowDate);	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatRecognition.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

//		Log.d(TAG,"callResult::"+callResult);
		/*
		 * 04-11 17:35:42.532: D/UsedMarketChatRest(3236): callResult::{
		 * "idUsedMarketChatRecognition":null,"phoneNumber":null,"readYn":null,"activateYn":null,"modifyDate":null,
		 * "registerDate":null,"usedMarketChatIdUsedMarketChat":null,"usedMarketChatIdUsedMarketProduct":null,
		 * "usedMarketChatOwner":null,"totalCount":null,
		 * "result":"SUCCESS"}
		 */
		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}

	/**
	 * RestSelectRecognition			selectRecognition	 	
	 *  인지 테이블의 사용자 정보를 가져 온다.	
	 * @return  String
	 */
	public String RestSelectRecognition(UsedMarketChatRecognition usedMarketChatRecognition){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_RECOGNITION_CONTROLLER+"/"+CommonConstant.SELECT_RECOGNITION;
		JSONObject obj = new JSONObject();
		try{
			obj.put("phoneNumber", usedMarketChatRecognition.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			//			obj.put("readYn", "Y");		
			obj.put("activateYn", "Y");		
			//			obj.put("modifyDate", nowDate);			
			//			obj.put("registerDate", nowDate);	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatRecognition.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		Log.d(TAG,"callResult::"+callResult);

		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}

	/**
	 * RestSelectRecognitionList			selectRecognitionList	 	
	 *  인지 테이블의 사용자 목록을 가져 온다.	
	 * @return  String
	 */
	public String RestSelectRecognitionList(UsedMarketChatRecognition usedMarketChatRecognition){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_RECOGNITION_CONTROLLER+"/"+CommonConstant.SELECT_RECOGNITION_LIST;
		JSONObject obj = new JSONObject();
		try{
			//			obj.put("phoneNumber", usedMarketChatRecognition.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			//			obj.put("readYn", "Y");		
			obj.put("activateYn", "Y");		
			//			obj.put("modifyDate", nowDate);			
			//			obj.put("registerDate", nowDate);	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatRecognition.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatRecognition.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		Log.d(TAG,"callResult::"+callResult);

		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}

	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * RestRegisterUser			registerUser	 	
	 *  채팅방에 사용자를 등록 한다.
	 * @return  String
	 */
	public String RestRegisterUser(UsedMarketChatUser usedMarketChatUser){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_USER_CONTROLLER+"/"+CommonConstant.REGISTER_USER;
		JSONObject obj = new JSONObject();
		try{
			obj.put("phoneNumber", usedMarketChatUser.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			obj.put("activateYn", "Y");		
			obj.put("modifyDate", nowDate);			
			obj.put("registerDate", nowDate);	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatUser.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatUser.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatUser.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		Log.d(TAG,"callResult::"+callResult);
		/*
		 * // 04-10 15:32:32.149: D/UsedMarketChatRest(6912): callResult::{
		 * "idUsedMarketChatUser":null,
		 * "phoneNumber":null,
		 * "activateYn":null,
		 * "modifyDate":null,
		 * "registerDate":null,
		 * "usedMarketChatIdUsedMarketChat":null,
		 * "usedMarketChatIdUsedMarketProduct":null,
		 * "usedMarketChatOwner":null,
		 * "totalCount":null,
		 * "result":"SUCCESS",
		 * "deviceType":null,"pushId":null}
		 */

		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);
				callResult = jsonObject.getString("result").toString(); 
			} catch (JSONException e) {
				callResult = "F";
				e.printStackTrace();
			} 
		}
		return callResult;
	}

	/**
	 * RestUpdateDeactivateUser			updateDeactivateUser	 	
	 *  채팅방 사용자를 비활성화 한다.
	 * @return  String
	 */
	public String RestUpdateDeactivateUser(UsedMarketChatUser usedMarketChatUser){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_USER_CONTROLLER+"/"+CommonConstant.UPDATE_DEACTIVATE_USER;
		JSONObject obj = new JSONObject();
		try{
			obj.put("phoneNumber", usedMarketChatUser.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			obj.put("activateYn", "N");		
			obj.put("modifyDate", nowDate);			
			//			obj.put("registerDate", nowDate);	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatUser.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatUser.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatUser.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		Log.d(TAG,"callResult::"+callResult);

		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}

	/**
	 * RestSelectUserList			selectUserList	 	
	 *  채팅방 사용자 목록을 가져 온다.
	 * @return  String
	 */
	public String RestSelectUserList(UsedMarketChatUser usedMarketChatUser){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_USER_CONTROLLER+"/"+CommonConstant.SELECT_USER_LIST;
		JSONObject obj = new JSONObject();
		try{
			//			obj.put("phoneNumber", usedMarketChatUser.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			obj.put("activateYn", "Y");		
			//			obj.put("modifyDate", nowDate);			
			//			obj.put("registerDate", nowDate);	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatUser.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatUser.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatUser.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		Log.d(TAG,"callResult::"+callResult);

		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}	

	/**
	 * RestSelectUser			selectUser	 	
	 *  채팅방 사용자 정보를 가져 온다.
	 * @return  String
	 */
	public String RestSelectUser(UsedMarketChatUser usedMarketChatUser){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_USER_CONTROLLER+"/"+CommonConstant.SELECT_USER;
		JSONObject obj = new JSONObject();
		try{
			
			Log.d(TAG,"phoneNumber:"+usedMarketChatUser.getPhoneNumber());
			Log.d(TAG,"usedMarketChatIdUsedMarketChat:"+usedMarketChatUser.getUsedMarketChatIdUsedMarketChat());
			Log.d(TAG,"usedMarketChatIdUsedMarketProduct:"+usedMarketChatUser.getUsedMarketChatIdUsedMarketProduct());
			Log.d(TAG,"usedMarketChatOwner:"+usedMarketChatUser.getUsedMarketChatOwner());
			
			obj.put("phoneNumber", usedMarketChatUser.getPhoneNumber());							// 사용자(생성자) 휴대전화번호.
			obj.put("activateYn", "Y");			// ### ??? N ?		
			//			obj.put("modifyDate", nowDate);			
			//			obj.put("registerDate", nowDate);	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatUser.getUsedMarketChatIdUsedMarketChat());
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatUser.getUsedMarketChatIdUsedMarketProduct());
			obj.put("usedMarketChatOwner", usedMarketChatUser.getUsedMarketChatOwner());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

//		Log.d(TAG,"callResult::"+callResult);

		/*
		 * "idUsedMarketChatUser":"13",
		 */
		
		// 서버 호출 결과 처리
//		if(!(callResult.equals("F"))){
//			try {
//				JSONObject jsonObject = new JSONObject(callResult);
//				callResult = jsonObject.getString("result").toString(); 		idUsedMarketChatUser
//			} catch (JSONException e) {
//				callResult = "F";
//				e.printStackTrace();
//			} 
//		}
		return callResult;
	}	

	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * RestRegisterMessage			registerMessage	 	
	 *  메시지를 등록 한다.
	 * @return  String
	 */
	public String RestRegisterMessage(UsedMarketChatMessage usedMarketChatMessage){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_MESSAGE_CONTROLLER+"/"+CommonConstant.REGISTER_MESSAGE;
		JSONObject obj = new JSONObject();
		try{
			
			obj.put("content", usedMarketChatMessage.getContent());
			obj.put("messageImage", usedMarketChatMessage.getMessageImage());
			obj.put("thumbnailLarge", usedMarketChatMessage.getThumbnailLarge());
			obj.put("thumbnailSmall", usedMarketChatMessage.getThumbnailSmall());
			obj.put("activateYn", "Y");	
			obj.put("modifyDate", nowDate);			
			obj.put("registerDate", nowDate);
			obj.put("usedMarketChatUserIdUsedMarketChatUser", usedMarketChatMessage.getUsedMarketChatUserIdUsedMarketChatUser());						
			obj.put("usedMarketChatUserPhoneNumber", usedMarketChatMessage.getUsedMarketChatUserPhoneNumber());						
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatMessage.getUsedMarketChatIdUsedMarketChat());						
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatMessage.getUsedMarketChatIdUsedMarketProduct());						
			obj.put("usedMarketChatOwner", usedMarketChatMessage.getUsedMarketChatOwner());						
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		Log.d(TAG,"callResult::"+callResult);

		// 서버 호출 결과 처리
		//		if(!(callResult.equals("F"))){
		//			try {
		//				JSONObject jsonObject = new JSONObject(callResult);
		//				callResult = jsonObject.getString("result").toString(); 
		//			} catch (JSONException e) {
		//				callResult = "F";
		//				e.printStackTrace();
		//			} 
		//		}
		return callResult;
	}		

	/**
	 * RestRegisterMessageWithImage			registerMessageWithImage	 	
	 *  메시지와 이미지를 등록 한다.
	 * @return  String
	 */
	public String RestRegisterMessageWithImage(UsedMarketChatMessage usedMarketChatMessage, Context context){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();
		
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_MESSAGE_CONTROLLER+"/"+CommonConstant.REGISTER_MESSAGE_WITH_IMAGE;
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost ;
		MultipartEntity mpEntity ;
		HttpResponse response = null;
		HttpEntity resEntity = null ;
		String callResult;

		try {
			httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
			httppost = new HttpPost(fullUrl);
			mpEntity = new MultipartEntity();
			//차후 수정 서버 부분 수정

			mpEntity.addPart("content", new StringBody(usedMarketChatMessage.getContent()));
			mpEntity.addPart("messageImage", new StringBody(""));
			mpEntity.addPart("thumbnailLarge", new StringBody(""));
			mpEntity.addPart("thumbnailSmall", new StringBody(""));
			mpEntity.addPart("activateYn", new StringBody("Y"));
			mpEntity.addPart("modifyDate", new StringBody(nowDate));
			mpEntity.addPart("registerDate", new StringBody(nowDate));
			
			mpEntity.addPart("usedMarketChatUserIdUsedMarketChatUser", new StringBody(usedMarketChatMessage.getUsedMarketChatUserIdUsedMarketChatUser()));
			mpEntity.addPart("usedMarketChatUserPhoneNumber", new StringBody(usedMarketChatMessage.getUsedMarketChatUserPhoneNumber()));
			mpEntity.addPart("usedMarketChatIdUsedMarketChat", new StringBody(usedMarketChatMessage.getUsedMarketChatIdUsedMarketChat()));
			mpEntity.addPart("usedMarketChatIdUsedMarketProduct", new StringBody(usedMarketChatMessage.getUsedMarketChatIdUsedMarketProduct()));
			mpEntity.addPart("usedMarketChatOwner", new StringBody(usedMarketChatMessage.getUsedMarketChatOwner()));
			
			// 이미지가 있으면 이미지를 보냄
			Bitmap selectedImg = usedMarketChatMessage.getUploadFileImg();

			//Convert bitmap to byte array
			ByteArrayOutputStream bos = new ByteArrayOutputStream();		// ByteArrayOutputStream 객체 bos 생성
			selectedImg.compress(Bitmap.CompressFormat.PNG, 0, bos);		// 이미지를 PNG로 변환하여 bos 에 저장
			byte[] data = bos.toByteArray();								// 이미지를 byte[] 형으로 꺼냄
			Log.d(TAG,"img size3:"+data.length);							// 파일 용량

			String fileName = usedMarketChatMessage.getUsedMarketChatUserPhoneNumber() + "_" + commonUtil.getNowDateForImage() + ".png";		// 이미지 이름 설정
			Log.d(TAG,"fileName::"+fileName);
			mpEntity.addPart("fileName", new StringBody(fileName));

			File file = new File(context.getCacheDir(), fileName);
			Log.d(TAG,"context.getCacheDir():"+context.getCacheDir());
			file.createNewFile();

			//write the bytes in file
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(data);
			fos.flush();
			fos.close();

			// 이부분의 설정으로 파일을 보낸다.
			ContentBody cbFile = new FileBody(file, "image/jpeg");
			mpEntity.addPart("file", cbFile);  //서버에서 처리해주는 파일이름이 file 이 되겠고, 내가 보내는 파일이 cbFile이다.	
			httppost.setEntity(mpEntity);
			response = httpclient.execute(httppost);
			resEntity = response.getEntity();
			if (resEntity != null) {
				String tmpStr = EntityUtils.toString(resEntity);
//				Log.d(TAG,"tmpStr:"+tmpStr);
				callResult = tmpStr;
			}else{
				Log.d(TAG,"resEntity == null");
				callResult = "F";
			}
			httpclient.getConnectionManager().shutdown();
		} catch (Exception e) {
			callResult = "F";
			e.printStackTrace();
		}
		return callResult;
	}	
	
	

	/**
	 * RestSelectMessageList			selectMessageList	
	 *  메시지 목록을 가져 온다.
	 * @return  String
	 */
	public String RestSelectMessageList(UsedMarketChatMessage usedMarketChatMessage){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CHAT_MESSAGE_CONTROLLER+"/"+CommonConstant.SELECT_MESSAGE_LIST;
		JSONObject obj = new JSONObject();
		try{
			obj.put("activateYn", "Y");	
			obj.put("usedMarketChatIdUsedMarketChat", usedMarketChatMessage.getUsedMarketChatIdUsedMarketChat());						
			obj.put("usedMarketChatIdUsedMarketProduct", usedMarketChatMessage.getUsedMarketChatIdUsedMarketProduct());						
			obj.put("usedMarketChatOwner", usedMarketChatMessage.getUsedMarketChatOwner());						
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

//		Log.d(TAG,"callResult::"+callResult);
		/*
		 * 04-14 12:08:23.055: D/UsedMarketChatRest(8059): callResult::[
		 * 
		 * {"idUsedMarketChatMessage":"1",
		 * 
		 * "content":"네네",																			//
		 * 
		 * "messageImage":"",
		 * "thumbnailLarge":"",
		 * "thumbnailSmall":"",
		 * 
		 * "activateYn":"Y",
		 * 
		 * "registerDate":"2014-04-14 11:58:14",													//
		 * 
		 * "usedMarketChatUserIdUsedMarketChatUser":"17",											// ?
		 * 
		 * "usedMarketChatUserPhoneNumber":null,
		 * 
		 * "usedMarketChatIdUsedMarketChat":"10",
		 * "usedMarketChatIdUsedMarketProduct":"40",
		 * "usedMarketChatOwner":"01022173645",
		 * 
		 * "totalCount":null,"result":null,
		 * "imagePath":null,"largeThumbnailPath":null,"smallThumbnailPath":null}]
		 * 
		 */
		return callResult;
	}	


	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	

	public String checkNull(String str){
		if(str==null || str.equals("null")){
			return "";
		}
		return str;
	}
	
	
	// 공용 서버 호출 메소드
	public String callServerMethod(String fullUrl, String inputJson){
		String callResult = "";
		try{
			URL postUrl = new URL(fullUrl);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
			connection.setConnectTimeout(CommonConstant.serverConnectTimeOut);
			connection.setDoOutput(true);
			connection.setInstanceFollowRedirects(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/json");

			OutputStream os = connection.getOutputStream();		// 여기서 타임아웃이 발생하는 경우가 있음
			os.write(inputJson.getBytes("UTF-8"));
			os.flush();

			int responseCode = connection.getResponseCode();
			InputStream in =  connection.getInputStream();
			if(responseCode==200 || responseCode==204){
				// 결과를 처리.
				BufferedReader reader = new BufferedReader(new InputStreamReader(in), 8192);
				StringBuilder builder = new StringBuilder();
				String line =null;
				try {
					while((line=reader.readLine())!=null){
						builder.append(line).append("\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				callResult = builder.toString();
			}else{
				Log.d(TAG,"responseCode:"+responseCode);
				callResult="F";
			}
		}catch(Exception e){ 
			e.printStackTrace();
			callResult="F";
		}
		return callResult;
	}	

}
